package com.crt.nexus.oauth.endpoint;

import com.google.common.base.Strings;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.minidev.json.JSONObject;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.security.KeyPair;
import java.security.interfaces.RSAPublicKey;
import java.util.Map;

import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.web.bind.annotation.RequestMethod.GET;

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/token")
public class TokenEndpoint {

    private final KeyPair keyPair;

    @RequestMapping(value = "jwks", method = GET, produces = APPLICATION_JSON_VALUE)
    public ResponseEntity<JSONObject> jwks() {
        RSAPublicKey publicKey = (RSAPublicKey) this.keyPair.getPublic();
        RSAKey key = new RSAKey.Builder(publicKey).build();
        return ResponseEntity.ok(new JWKSet(key).toJSONObject());
    }

    @RequestMapping(value = "check", method = GET, produces = APPLICATION_JSON_VALUE)
    public ResponseEntity<Map<String, Object>> check(HttpServletRequest request) {
        String token = request.getParameter("token");
        if (Strings.isNullOrEmpty(token)) throw new BadCredentialsException("令牌不能为空");
        RSAPublicKey publicKey = (RSAPublicKey) this.keyPair.getPublic();
        Jwt jwt = NimbusJwtDecoder.withPublicKey(publicKey).build().decode(token);
        return ResponseEntity.ok(jwt.getClaims());
    }

}
